# -*- coding:utf-8 -*-
from google.appengine.ext import db
from google.appengine.api import users
from ytbase.setting import *
from ytbase.exceptions import YTError

TYPE_GA = 'ga'
TYPE_FB = 'fb'
TYPE_XN = 'xn'
TYPE_KX = 'kx'
TYPE_FO = 'fo'
TYPE_XM = 'xm'
TYPE_EM = 'em'
TYPE_ST = 'st'

AUTH_TYPE_OAUTH = 'OAuth'

def normalize_jid(jid):
    import re
    pattern = re.compile(u'([^/]*)/?([^/]*)')
    match = pattern.match(jid)    
    return (match.group(1).lower(),u'')

class YTUser(db.Expando):
    ext = db.ReferenceProperty(collection_name='ytuser_ext_set') 

    name = db.StringProperty(multiline=False)
    first_name = db.StringProperty(multiline=False)
    last_name = db.StringProperty(multiline=False)

    description = db.TextProperty()
    address = db.StringProperty(multiline=False)

    count = db.IntegerProperty(default=0)
    recommend_count = db.IntegerProperty(default=0)
    comment_count = db.IntegerProperty(default=0)   
    charm_points = db.IntegerProperty(default=0)
    date_joined = db.DateTimeProperty(auto_now_add=True)
    valid_from = db.DateTimeProperty()
    valid_to = db.DateTimeProperty()
    
    is_superuser = db.BooleanProperty(default=False)
    type = db.StringProperty(multiline=False)
    uid = db.StringProperty(multiline=False)
    auth_type = db.StringProperty(multiline=False)
    ga = db.UserProperty(auto_current_user_add=True)
    email = db.EmailProperty()
    
    friends = db.ListProperty(db.Key)
    tags = db.StringListProperty()

    @classmethod
    def get_user_key(cls, user):
        if isinstance(user, db.Model):
            return user.key()
        elif isinstance(user, db.Key):
            return user
        else:
            return None  
        
    @classmethod
    def get_user_obj(cls, user):
        if isinstance(user, db.Model):
            return user
        elif isinstance(user, db.Key):
            return db.get(user)
        else:
            return None    
        
    @classmethod
    def get_users_by_name(cls, name, num=1, type=None):
        users_query = cls.all().filter('name = ', name)
        if type:
            users_query = users_query.filter('type =', type)
        
        if num > 1:
            return users_query.fetch(num)
        else:
            return users_query.get()
        
    @classmethod
    def get_user(cls, type, *args, **kwds):
        if type == TYPE_GA:
            ga_user = users.get_current_user()
            if not ga_user:
                raise YTError, 'invalid user'
            
            key = TYPE_GA + ga_user.user_id()
            user = YTUser.get_by_key_name(key)
      
            if not user:
                user = YTUser.get_or_insert(key_name=key, type=TYPE_GA, ga=ga_user)
        
            return user
            
        if type == TYPE_EM and kwds.has_key('email'):
            key = TYPE_EM + kwds['email']
            user = YTUser.get_by_key_name(key)
              
            if not user:
                user = YTUser.get_or_insert(key_name=key, type=TYPE_EM, email=kwds['email'])
                
            return user

        if type == TYPE_XM and kwds.has_key('jid'):
            jid, res = normalize_jid(kwds['jid'])
            key = TYPE_XM + jid
            user = YTUser.get_by_key_name(key)
              
            if not user:
                user = YTUser.get_or_insert(key_name=key, type=TYPE_XM, uid=jid)
                
            return user

        #sina user
        if type == TYPE_ST and kwds.has_key('uid'):
            key = TYPE_ST + kwds['uid']
            user = YTUser.get_by_key_name(key)
            
            if not user:
                if kwds.has_key('name'):
                    user = YTUser.get_or_insert(key_name=key, 
                                                type=TYPE_ST, 
                                                uid=kwds['uid'], 
                                                name=kwds['name'])
            elif kwds.has_key('name') and user.name != kwds['name']:
                user.name = kwds['name']
                user.put()               
                
            return user
        
        raise YTError, 'invalid user'
        
    @classmethod
    def get_key(cls, type, *args, **kwds):
        if type == TYPE_GA:
            ga_user = users.get_current_user()
            if not ga_user:
                raise YTError, 'invalid key'
            
            key = TYPE_GA + ga_user.user_id()
            return Key.from_path('YTUser', key)
        
        if type == TYPE_EM and kwds.has_key('email'):
            key = TYPE_EM + kwds['email']
            return Key.from_path('YTUser', key)

        if type == TYPE_XM and kwds.has_key('jid'):
            jid, res = normalize_jid(kwds['jid'])
            key = TYPE_XM + jid
            return Key.from_path('YTUser', key)

        if type == TYPE_ST and kwds.has_key('uid'):
            key = TYPE_ST + kwds['uid']
            return Key.from_path('YTUser', key)

        raise YTError, 'invalid key'
    
    def put(self):
        db.Model.put(self)
    
    def get_name(self):
        return self.ga.nickname()
